package com.tjmc.nsia.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.tjmc.nsia.core.constant.ErrorCodeEnum;
import com.tjmc.nsia.core.exception.BusinessException;
import com.tjmc.nsia.core.service.ResourceService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Luc
 * @version 1.0
 * @date 2024-07-04 23:03
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    @Value("${nsia.file.upload.path}")
    private String fileUploadPath;

    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        LocalDateTime now = LocalDateTime.now();
        String savePath = "/file/"
                        + now.format(DateTimeFormatter.ofPattern("yyyy")) + "/"
                        + now.format(DateTimeFormatter.ofPattern("MM")) + "/"
                        + now.format(DateTimeFormatter.ofPattern("dd"));
        String oriName = file.getOriginalFilename();
        String saveFileName = IdWorker.get32UUID() + "_"+  oriName.substring(oriName.lastIndexOf("."));
        File saveFile = new File(fileUploadPath + savePath, saveFileName);
        if (!saveFile.getParentFile().exists()) {
            boolean isSuccess = saveFile.getParentFile().mkdirs();
            if (!isSuccess) {
                throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_ERROR);
            }
        }
        file.transferTo(saveFile);
        return savePath + "/" + saveFileName;
    }
}
